const express = require("express");
const app = express();
const path = require("path");
const server = require("http").createServer(app);
const io = require("socket.io").listen(server).sockets;
app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});
//static

let connectedUser = [];

app.use(express.static(path.join(__dirname, "node_modules")));
//  Socket.io connect
io.on("connection", socket => {
  console.log("a user connected~");
  updateUserName();
  let userName = "";

  //login
  socket.on("login", (name, callback) => {
    if (name.trim().length === 0) {
      return;
    }
    callback(true);
    userName = name;
    connectedUser.push(userName);
    updateUserName();
  });
  //Receive Chat Message
  socket.on("chat message", msg => {
    console.log("msg", msg);
    io.emit("output", {
      name: userName,
      msg: msg
    });
  });

  //Disconnect
  socket.on("disconnect", () => {
    console.log("user disconnected");
    let logoutmsg = `${userName} left the chat room`
    socket.emit('logout', logoutmsg);
    connectedUser.splice(-1 === connectedUser.indexOf(userName) ? 99999 : connectedUser.indexOf(userName), 1);
    updateUserName();
  });

  //update username
  function updateUserName() {
    console.log(connectedUser);
    io.emit("loadUser", connectedUser);
  }
});

const port = process.env.PORT || 8888;
server.listen(port, () => {
  console.log(`Server running on port ${port}`);
});